﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using Neodynamic.SDK.ImageDraw;

namespace TransLogger.Module
{
    public class Util
    {
        public static Image ResizePortraitImage(Image img)
        {
            var imgDraw = new ImageDraw();
            imgDraw.ImageFormat = ImageDrawFormat.Jpeg;
            imgDraw.Canvas.AutoSize = true;
            var imgelem = ImageElement.FromImage(img);

            var width = img.Height * 0.9;
            var crop = new Crop();
            crop.X = (int)((img.Width - width) / 2);
            crop.Y = 0;
            crop.Width = (int)width;
            crop.Height = img.Height;

            var resize = new Resize();
            resize.Width = 250;
            resize.LockAspectRatio = LockAspectRatio.WidthBased;

            imgelem.Actions.Add(crop);
            imgelem.Actions.Add(resize);

            imgDraw.Elements.Add(imgelem);
            return imgDraw.GetOutputImage();
        }

        public static Image ResizeImage(Image img, int width)
        {
            var imgDraw = new ImageDraw();
            imgDraw.ImageFormat = ImageDrawFormat.Jpeg;
            imgDraw.Canvas.AutoSize = true;
            var imgelem = ImageElement.FromImage(img);


            var resize = new Resize();
            resize.Width = width;
            resize.LockAspectRatio = LockAspectRatio.WidthBased;

            imgelem.Actions.Add(resize);

            imgDraw.Elements.Add(imgelem);
            return imgDraw.GetOutputImage();
        }

        public static Image LoadFrom(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            var bytes = File.ReadAllBytes(path);
            var stream = new MemoryStream(bytes);
            
                return Image.FromStream(stream);
            
        }
    }
}
